package com.shuqi.controller;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.shuqi.activity.ActivityBase;
import com.shuqi.activity.BookShelfActivity;
import com.shuqi.activity.NewbieGuideActivity;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.Config;
import com.shuqi.common.FunctionsSwitch;
import com.shuqi.common.InlayBook;
import com.shuqi.common.LoadingImg;
import com.shuqi.common.MyTask;
import com.shuqi.common.Urls;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.SharedPreferenceUtil;
import com.shuqi.common.utils.Util;
import com.shuqi.database.dao.impl.BookMarkInfoDao;
import com.shuqi.database.model.BookMarkInfo;
import com.shuqi.database.model.UserInfo;
import com.shuqi.interfaces.WatingListener;
import com.shuqi.model.manager.MyAccountManager;
import com.shuqi.model.manager.SoftCofigManager;
import com.shuqi.sdk.ad.ADView;
import com.shuqi.sdk.ad.ADViewLoading;
import com.shuqi.sdk.ad.ADViewLoading.LoadingADLinstener;
import com.shuqi.service.CheckMarksUpdateService;
import com.shuqi.service.CheckPushMessageService;
import com.shuqi.service.ConnectionChangeReceiver;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

/**
 * Loading软件的启动页
 * 
 * @author Jianda.Yang
 * @date 2013-12-12 下午4:48:23
 * @version 1.0
 */
public class Loading extends ActivityBase {
    private final String logTag = "Loading";
    /** 启动页的展示时间 */
    private int LoadingTime = 500;

    private final int MSG_InitData_start = -1;
    private final int MSG_InitData_finish = -2;
    private final int MSG_InitUser_start = -3;
    private final int MSG_InitUser_finish = -4;
    private final int MSG_Allfinish = -5;

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_InitData_start:
                    initSoftWare();
                    break;
                case MSG_InitData_finish:
                case MSG_InitUser_start:
                    onCheckConfigAndUser();
                    break;
                case MSG_InitUser_finish:
                    onReadyDelayed();
                    break;
                case MSG_Allfinish:
                    onOpenSoft();
                    if (ADViewLoading.isOpenADViewLoading) {
                        updateAdData();
                    }
                    break;
            }
        };
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ShuqiApplication.callShuQiIsRunning();
        super.onCreate(savedInstanceState);
        initViewLoading();
        StatisticsUtils.onEvent(this, StatisticsEventID.APP_START);

    }

    /**
     * 更新开屏广告数据
     */
    private void updateAdData() {
        if (Util.isNetworkConnected(this)) {
            ADView myADView =
                    new ADView(this, 5, Urls.getAdvertisingURL(this, 5), String.valueOf(Util
                            .getVersionCode(this)), -1);
            myADView.checkIsAdShown(true);
        }
    }

    private void initViewLoading() {
        setContentView(R.layout.layout_loading);
        findViewById(R.id.loading_splash).setBackgroundDrawable(
                LoadingImg.getLoadingPic(this, SharedPreferenceUtil.PicPathKey,
                        Config.DEFAULT_PATH_LOADINGPIC));
        if (ADViewLoading.isOpenADViewLoading) {
            loadADViewLoading();
        } else {
            handler.sendEmptyMessage(MSG_InitData_start);
        }
    }

    private void loadADViewLoading() {
        // 判断开屏广告是否需要展示
        if (ADViewLoading.isShowAd(Loading.this)) {
            ADViewLoading.getInstance(Loading.this, new LoadingADLinstener() {
                @Override
                public void onSplashEnd() {
                    handler.sendEmptyMessage(MSG_InitData_start);
                }

                @Override
                public void onShowAd(Context context, String name) {
                    Log4an.d(logTag, "自主开屏广告准备好了，开始展示");
                    LoadingTime = 2000;
                    int h = (Util.getScreenHeight() / 4) * 3;
                    ImageView imageView = (ImageView) findViewById(R.id.loading_ad_splash);
                    RelativeLayout.LayoutParams rl =
                            new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, h);
                    imageView.setLayoutParams(rl);
                    imageView.setImageDrawable(LoadingImg.getLoadingAdPic(context, name));
                    StatisticsUtils.onEvent(context, StatisticsEventID.AD_VIEW_LOADING_SHOW);
                }
            });
        } else {
            handler.sendEmptyMessage(MSG_InitData_start);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            ADViewLoading.destoryAdView();
        } catch (Exception e) {
            e.printStackTrace();
            Log4an.d(logTag, "【loading onDestroy】e="+e.toString());
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        ShuqiApplication.callShuQiIsRunning();
        Log4an.e(logTag, "onNewIntent()" + intent);
        super.onNewIntent(intent);
    }

    private void onReadyDelayed() {
        CheckMarksUpdateService.startCheckBookMarksUpdate(getApplicationContext());
        CheckPushMessageService.startCheckPushMessageUpdate(getApplicationContext());
        // 导入预置书籍
        UserInfo info = MyAccountManager.getInstance(getApplicationContext());
        if (info != null) {
            if (Util.isCanUseSdCard()) {
                List<BookMarkInfo> liMarkInfos = null;
                liMarkInfos =
                        BookMarkInfoDao.getInstance().getBookShefBookMarkList(info.getUserId());
                Log4an.e(logTag, "预置书导入 info.getUserId() " + info.getUserId());
                Log4an.e(logTag, "liMarkInfos=" + (liMarkInfos == null ? true : liMarkInfos.size()));
                if (SharedPreferenceUtil.getInlayBookFirst(getApplicationContext()) == true
                        && (liMarkInfos == null || liMarkInfos.size() == 0)) {
                    InlayBook.synInlayBook(getApplicationContext());
                }
            }
        }
        handler.sendEmptyMessageDelayed(MSG_Allfinish, LoadingTime);
    }

    /** Intent int 参数：事件类型 */
    public static final String INTENT_ACTIONTYPE = "Action_Type";
    /** Loading action事件类型 ：打开书城 */
    public static final int ACTIONTYPE_OPENMAIN = 200;
    /** Loading action事件类型 ：打开书架 */
    public static final int ACTIONTYPE_OPENSHELF = 201;
    /** Loading action事件类型 ：打开阅读页 */
    public static final int ACTIONTYPE_OPENREAD = 202;
    /** Loading action事件类型 ：无 */
    public static final int ACTIONTYPE_NONE = -1;

    private void onOpenSoft() {
        Util.createShorCut(getApplicationContext());// 创建桌面快捷方式
        MainController.getMainManagerInstance();
        if (!FunctionsSwitch.isShowedNewbieGuide(this)) {
            NewbieGuideActivity.show(this, false);
            FunctionsSwitch.showedNewbieGuide(this, true);
        } else {
            BookShelfActivity.showFromLoading(this, true);
        }
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        finish();
    }

    private void onCheckConfigAndUser() {
        // appinfo接口访问
        SoftCofigManager.getInstance().loadSoftConfigInfo(getApplicationContext());
        // 用户验证检测
        MyAccountManager.onLoadingCheckUser(getApplicationContext(), new WatingListener() {
            @Override
            public void onFinish(boolean isSuccess) {
                // 通过开启软件身份检查完成
                handler.sendEmptyMessage(MSG_InitUser_finish);
            }

            @Override
            public void onBeforeNetWorking() {

            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = getIntent();
        if("open".equals(intent.getStringExtra("push_update"))){
            StatisticsUtils.onEvent(Loading.this,StatisticsEventID.PUSHMESSAGE_UPDATE_OPEN);
        }
    }

    /**
     * 初始化软件各种设置，log打印，网络状态，检查书籍更新，清理旧数据
     */
    private void initSoftWare() {
        Log4an.init(this, Config.ROOT_PATH);
        ConnectionChangeReceiver.getNetType(this);// 获取当前网络类型
        MyTask.runInBackground(new Runnable() {
            @Override
            public void run() {
                Log4an.e(logTag, "检查软件升级时数据导入和清理：开始");
                checkOnFirstOpenAfterUpdate();
                Log4an.e(logTag, "检查软件升级时数据导入和清理：完成");
                handler.sendEmptyMessage(MSG_InitData_finish);
            }
        }, true);
    }

    /**
     * 软件 升级/新安装 ，并且是第一次打开时：需要自行的操作的操作（数据库升级，清理冗余数据等……）
     */
    private void checkOnFirstOpenAfterUpdate() {
        if (FunctionsSwitch.isUpdateOrNewInstall(this)) {
            Log4an.e(logTag, "新安装|升级 第一次打开--->");
            FunctionsSwitch.showedNewbieGuide(this, false);
            if (FunctionsSwitch.isUpdateBefore(this, Config.VERSION_INFO)) {
                MyAccountManager.importUserInfoFromOldDB(getApplication());
                clearOldSharedPreferencesBeforeVersion8();
            }
            
            FunctionsSwitch.updateAndSaveVersion(this);
            // dealNewGuideIntent();
        }
    }

    // TODO
    private void dealNewGuideIntent() {
        Intent intent = getIntent();
        if (intent == null) {
            intent = new Intent();
            setIntent(intent);
        }
        intent.putExtra(BookShelfActivity.INTENT_SHOWGUIDE, true);
        Log4an.e(logTag, "dealNewGuideIntent 显示引导图 ");
    }

    /** 清理8.0之前的垃圾 SharedPreferences数据 */
    private void clearOldSharedPreferencesBeforeVersion8() {
        String[] spNames =
                {"checkad2", "checkad3", "config", "info_fail", "infos", "neterror", "pv2",
                        "serverlist", "setting", "settings", "shortcut", "TxtFileEncodings",
                        "TxtTotalCharacters", "weburls", "acount"};
        for (int i = 0; i < spNames.length; i++) {
            getSharedPreferences(spNames[i], Context.MODE_PRIVATE).edit().clear().commit();
        }
        Log4an.e(logTag, "清理OldSharedPreferences：完成 ");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void activityLogicForward() {}

    @Override
    public void activityInitData() {}
}
